//
//  WSOrderDetailViewController.m
//  FD
//
//  Created by xiaofang wang on 2018/10/31.
//  Copyright © 2018年 ZhiYuan Network. All rights reserved.
//  外送订单详情

/**
 0，支付，4评价，其他都是再来一单
 */

#import "WSOrderDetailViewController.h"
//model
#import "WSOrderBigModel.h" // 有用数据单独转换
#import "WSOrderCanPinMsgModel.h" //餐品信息
#import "WSOrderMsgModel.h" //订单信息
#import "OrderFooterCenterTableViewCellModel.h"

//view
#import "WSOrderHeaderView.h" //表头，frame、有外面设置好了再传进来
//#import "OrderFooterView.h" //表尾 ,子类需要访问 b暴露 h: ((44*3+10) + 50*8 + 80)
#import "WSOrderStateView.h"
#import "WSOrderEvaluateView.h" //星级评星(骑手信息)
#import "WSOrderMapView.h"
#import "WSOrderDetailCell.h" //1-9
#import "WSOrderDetailSectionHeaderView.h" //1-9
#import "XLAlertView.h" //弹框2019-2-13

//controller
#import "EvaluateController.h" //评价
#import "WSZaiLaiYiDanViewController.h" //再来一单(定义枚举进行区分)
#import "WSPayUrlViewController.h" //11-29跳转支付链接接口


//转门负责数据解析
#import "WSOrderDetailDataResolveTool.h"
#import "FDSystemTool.h" //打电话弹框

//下载骑手坐标，是订单状态 status=3，配送中，才建立连接， 其它状况不需要建立连接
//2019-1-5 websockettool 下载骑手坐标
//挪到 WSOrderMapView
//#import "FDOrderDetailWebSocketTool.h"

#import "WSOrderDetailTableViewProxy.h" //抽取tableView代理方法
#import "FDPaytypeAlertTool.h" //2019-2-13

@interface WSOrderDetailViewController ()

/**tv*/
@property (nonatomic,  strong) UITableView *tv;
/**sectionArr*/
@property (nonatomic,  strong) NSArray *sectionArr;

/**表头*/
@property (nonatomic, strong) WSOrderHeaderView *headerView;

/**表尾*/
@property (nonatomic,  strong) OrderFooterView *footerView;

/**模型-1 WSOrderBigModel.*/
@property (nonatomic, strong) WSOrderBigModel *bigModel;

/**tableViewProxy*/
@property (nonatomic, strong) WSOrderDetailTableViewProxy *tableViewProxy;

@end

@implementation WSOrderDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupView]; //布局
    [self loadOrderDetailDataWithOrderID:self.orderId]; //请求数据
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.headerView closeWebSocket]; //关闭websocket连接
}

- (void)setupView {
    self.navigationItem.title = NSLocalizedString(Home_OrderDetail, @"订单详情");
    self.view.backgroundColor = [UIColor whiteColor];
    
    //初始化数据源
    //    [self initDataArr];
    self.tv.frame = self.view.bounds;
    [self.view addSubview:self.tv];
    self.tv.tableFooterView = self.footerView;
    //国际化
    NSString *cpxxStr = NSLocalizedString(Home_CanPinMsg, @"餐品信息");
    NSString *ddxxStr = NSLocalizedString(OrderMessage, @"订单信息");
    self.sectionArr = @[cpxxStr,ddxxStr]; //给个空字符串就不会显示了
}

/**
 根据服务器返回的status字段，更新表头view
 
 @param status 服务器返回的数据
 备注 如果订单状态为：6 7 8，三个状态中任意一个，会显示这个(取消订单、退款中、退款成功)
 如果订单状态为：1 2 3 4 5， 五个状态中任意一个 会显示这个(已下单、制作中、派送中、已完成)
 */
- (void)updateTableViewHeaderViewWithStatus:(NSNumber *)status orderId:(NSString *)orderId {
    //表头由三种view决定。(订单状态、地图、评价)
    //订单状态高度
    CGFloat orderStateViewHeight = 100;
    //地图高度
    CGFloat mapViewHeight = 300;
    //评价高度
    CGFloat evaluteViewHeight = 80;
    
    CGFloat h = 0;
    
    //订单状态为
    NSArray *orderStateArr1 = @[@1,@2,@3,@4,@5,@6,@7,@8];
    if ([orderStateArr1 containsObject:status]) {
        h+= orderStateViewHeight+5;
    }
    
    
    
    
    
    
    
    //!!!!:2019-2-14展示骑手信息
    //订单状态为:3、4、5、6、7、8 展示骑手信息
    NSArray *orderStateArr2 = @[@3,@4,@5,@6,@7,@8];
    if ([orderStateArr2 containsObject:status]) {
        h+=evaluteViewHeight;
    }
    
    //订单状态 3:显示地图
    NSInteger zhuagnTai = [status integerValue];
    if (zhuagnTai == 3) {
        h+= mapViewHeight+5; //显示地图
        //不能再这里调用。因为header还没有new 出来
//        //2019-1-5建立socket链接下载骑手坐标 视图将要消失的时候取消socket连接。
//        [self.headerView estimateWebSocketConnectionWithOrderId:self.orderId];
    }
    
    FDLog(@"%f",h); //0.0000 头部间距太大。
    if (h > 1) {
        CGRect frame = CGRectMake(0, 0, SCREEN_WIDTH, h);
        WSOrderHeaderView *headerView = [[WSOrderHeaderView alloc] initWithFrame:frame orderStatus:status orderId:orderId];
        self.headerView = headerView; //指针重指向
        self.tv.tableHeaderView = headerView;
        
        //2019-2-18 修改逻辑
        if (zhuagnTai == 3) {
            //2019-1-5建立socket链接下载骑手坐标 视图将要消失的时候取消socket连接。
            [self.headerView estimateWebSocketConnectionWithOrderId:self.orderId];
        }
    }
}


#pragma mark - getter
- (WSOrderDetailTableViewProxy *)tableViewProxy {
    if (!_tableViewProxy) {
        _tableViewProxy = [[WSOrderDetailTableViewProxy alloc] init];
    }
    return _tableViewProxy;
}


- (UITableView *)tv {
    if (!_tv) {
        _tv = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStyleGrouped)]; //grouped as可以取消粘连效果
        //!!!!:WSOrderDetailTableViewProxy.h
        _tv.delegate = self.tableViewProxy;
        _tv.dataSource = self.tableViewProxy;

        _tv.separatorStyle = UITableViewCellSeparatorStyleNone; //取消线
        
        //注册cell
        [_tv registerClass:[WSOrderDetailCell class] forCellReuseIdentifier:@"WSOrderDetailCell"];
        [_tv registerClass:[WSOrderDetailSectionHeaderView class] forHeaderFooterViewReuseIdentifier:@"WSOrderDetailSectionHeaderView"]; //sectionHeaderView
        
    }
    return _tv;
}
- (OrderFooterView *)footerView {
    if (!_footerView) {
        //((44*3+10) + 50*8 + 60)
        
        _footerView = [[OrderFooterView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ((44*3+10) + 50*8 + 60))];
        _footerView.delegate =self;
    }
    return _footerView;
}

#pragma mark - 请求数据
- (void)loadOrderDetailDataWithOrderID:(NSString *)orderId
{
    if ([NSString isEmptyString:orderId]) {
        FDLog(@"订单id不能为空");
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [FDHttpAPi requestUserOrderDetailOrderId:orderId successBlock:^(id responseObjc) {
        
        [hud hideAnimated:YES];
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) { //解析数据
            
            NSDictionary *dataDic = responseObjc[@"data"];
            
            
            //解析数据
            [self resolvingDataWithDic:dataDic];
            
        }else { //错误提示
            [JRToast showWithText:responseObjc[describe]];
        }
    } failBlock:^(NSError *error) {

        [hud hideAnimated:YES];
    }];
}


/** 解析数据 */
- (void)resolvingDataWithDic:(NSDictionary *)dic {
    //专门搞个类进行数据解析
    self.bigModel = [WSOrderDetailDataResolveTool resolvingOrderBigModelWithDic:dic];
    
    self.shopPhone = self.bigModel.shopPhone; //2019-2-18子类使用
    
//[WSOrderDetailDataResolveTool resolvingCanPinMsgDataWithDic:dic]; //解析餐品信息数组
    [WSOrderDetailDataResolveTool resolvingOrderMsgDataWithDic:dic]; //解析订单信息数据
    
    
    
    NSArray *proxyDataArr =  [WSOrderDetailDataResolveTool xinResolvingTableViewDataWithDic:dic];
    
    //上
    
    
    //中
    NSArray *centerTableViewArr = [WSOrderDetailDataResolveTool resolvingOrderMsgDataWithDic:dic]; //解析订单信息数据
    
    //下
    
    //回到主线程中刷新数据
    dispatch_async(dispatch_get_main_queue(), ^{
        
        //更新表头数据 & 请求订单转态数据
        [self updateTableViewHeaderViewWithStatus:self.bigModel.status orderId:self.bigModel.orderId];
        
        [self.headerView showDefaultShopLocationLng:self.bigModel.shopLng lat:self.bigModel.shopLat name:self.bigModel.shopName]; //显示店铺大头针
        [self.headerView showReceiveAddressMarkerWithLng:self.bigModel.longitude lat:self.bigModel.latitude name:self.bigModel.detail]; //2019-2-18显示收货地址大头针
        
        
        //1-10已经优惠 = 订单总额-实付金额
        CGFloat youhui = [self.bigModel.totalAmount floatValue] - [self.bigModel.actualAmount floatValue];
        [self.footerView updateTopCouponFreightViewWithCoupon:self.bigModel.couponAmount freight:self.bigModel.freightAmount alreadyCoupon:youhui sum:self.bigModel.actualAmount];
        
        [self.footerView updateCenterTableViewDataArray:centerTableViewArr];
        //11-27更新底部文字
        [self.footerView updateRightBtnTitleWithStatus:self.bigModel.status payType:self.bigModel.paymentType deliveryType:@(0)]; //deliveryType:0外送
        
        //1-9 给proxy设置代理
        self.tableViewProxy.dataArray = proxyDataArr;
        
        //刷新tableView
        [self.tv reloadData];
    });
}

//子类实现
#pragma mark -  OrderFooterViewDelegate 点击事件回调

- (void)clickOrderFooterViewActionType:(OrderFooterViewActionType)actionType {
    switch (actionType) {
        case OrderFooterViewActionLeft: {
            FDLog(@"左边的");
            if ([NSString isEmptyString:self.bigModel.shopPhone]) {
                FDLog(@"电话号码为空，操作无效");
                return;
            }
            
            FDLog(@"电话号码应该有问题:%@",self.bigModel.shopPhone);
            
            [FDSystemTool fd_makePhone:self.bigModel.shopPhone];
        } break;
            
        case OrderFooterViewActionTypeRight: {
            
            NSNumber *status = self.bigModel.status;
            NSNumber *paytype = self.bigModel.paymentType;
            FDLog(@"status:%@ paytype:%@",status,paytype);
            
            //在线支付显示逻辑 payementType:0 status:0 显示
            //payementType:1 status:0,1,2,3 显示
            
            //再来一单显示逻辑 status:5,6,7,8,9 显示
            
            //评价显示逻辑 status:4
            
            if ([paytype isEqualToNumber:@(0)] &&
                [status isEqualToNumber:@(0)]) { //立即支付弹框(在线支付、线下支付)
                
                [self alertTwoPayType];
                
            }else if ([paytype isEqualToNumber:@(1)]) { //立即支付弹框(在线支付)
                if ([status isEqualToNumber:@(0)] ||
                    [status isEqualToNumber:@(1)] ||
                    [status isEqualToNumber:@(2)] ||
                    [status isEqualToNumber:@(3)]) {
                    
                    [self alertOnePayType];
                }else if ([status isEqualToNumber:@(4)]) { //2019-2-18
                    FDLog(@"评价");
                    [self skipToEvaluate];
                }
                
            }else if ([status isEqualToNumber:@(4)]) { //评价
                [self skipToEvaluate];
            }else if([status isEqualToNumber:@(5)]||
                     [status isEqualToNumber:@(6)]||
                     [status isEqualToNumber:@(7)]||
                     [status isEqualToNumber:@(8)]||
                     [status isEqualToNumber:@(9)]){ //再来一单
                [self skipToZaiLaiYiDan];
            }else if([paytype isEqualToNumber:@(0)] &&
                     [status isEqualToNumber:@(3)]) { //2019-2-18 再来一单 &&
                [self skipToZaiLaiYiDan];
            }else if([paytype isEqualToNumber:@(0)] &&
                     [status isEqualToNumber:@(1)]) { //2019-2-20 status:1/2/3都是 ‘再来一单’
                [self skipToZaiLaiYiDan];
            }else if ([paytype isEqualToNumber:@(0)] &&
                      [status isEqualToNumber:@(2)]) { //2019-2-20 再来一单 还是要判断 paytype
                [self skipToZaiLaiYiDan];
            }else {
                FDLog(@"其他状态不处理");
            }
        }
        default:
            break;
    }
}

- (void)alertTwoPayType {
    
    [FDPaytypeAlertTool showAlertTwoPaytypePayOnlineBlock:^{
        [self requestPayOnline];
    } offlineBlock:^{
        [self requestPayOffline];
    }];
}

- (void)alertOnePayType {
    
    [FDPaytypeAlertTool showAlertOnePayTypeOnlinePayBlock:^{
        [self requestPayOnline];
    }];
}

//!!!!:支付方式
//线上
- (void)requestPayOnline {
    [FDHttpAPi requestPayOnlineWithOrderId:self.orderId successBlock:^(id responseObjc) {
        
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {
            NSString *urlStr = responseObjc[@"data"][@"url"];
            WSPayUrlViewController *payVC = [[WSPayUrlViewController alloc] init];
            payVC.payUrl = urlStr;
            [self.navigationController pushViewController:payVC animated:YES];
        }else {
            [JRToast showWithText:responseObjc[describe]];
        }
    } failBlock:^(NSError *error) {
        FDLog(@"%@",[error localizedDescription]);
    }];
}

//线下 点击“线下支付”按钮，调用接口(88号)：/user/order/payment/offline 接口调用成功后，刷新当前订单列表即可
- (void)requestPayOffline {
    [FDHttpAPi requestPayOfflineWithOrderId:self.orderId successBlock:^(id responseObjc) {
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {
            //刷新列表
            [self loadOrderDetailDataWithOrderID:self.orderId];
        }else {
            [JRToast showWithText:responseObjc[describe]];
        }
        
    } failBlock:^(NSError *error) {
        FDLog(@"%@",[error localizedDescription]);
    }];
}




- (void)skipToEvaluate {
    EvaluateController *evaluateVC = [[EvaluateController alloc] init];
    evaluateVC.fdDeliveryType = FDDeliveryTypeWaiSong; //外送评价
    evaluateVC.userOrderId = self.orderId;
    [self.navigationController pushViewController:evaluateVC animated:YES];
}

- (void)skipToZaiLaiYiDan {
    WSZaiLaiYiDanViewController *zaiLaiYiDanVC = [[WSZaiLaiYiDanViewController alloc] init];
    zaiLaiYiDanVC.userOrderId = self.bigModel.orderId;
    //判空处理:只有不为空的时候才会进行跳转
    if ([NSString isEmptyString:self.bigModel.orderId]) { //如果是空的就不进行跳转条件别判断反了
        [JRToast showWithText:@"userOrderId 为空无法跳转"];
        return;
    }
    [self.navigationController pushViewController:zaiLaiYiDanVC animated:YES];
}

/**立即支付.获取订单支付链接*/
- (void)skipToPayUrlVCWithOrderID:(NSString *)orderId {
    
    [MBProgressHUD fd_showHUDToView:self.view];
    
    [FDHttpAPi requestUserOrderPaymentUrlWithOrderId:orderId successBlock:^(id responseObjc) {
    
        [MBProgressHUD fd_hideHUDFromView:self.view];
        
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {
            FDLog(@"%@",responseObjc[@"data"][@"url"]);
            
            WSPayUrlViewController *payurlVC = [[WSPayUrlViewController alloc] init];
            payurlVC.payUrl = responseObjc[@"data"][@"url"];
            [self.navigationController pushViewController:payurlVC animated:YES];
        }
    } fialBlock:^(NSError *error) {
        FDLog(@"%@",[error localizedDescription]);
        
        [MBProgressHUD fd_hideHUDFromView:self.view];
    }];
}

@end

